package com.wws.family.ui.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.UnitDateFormatter
import com.github.gzuliyujiang.wheelpicker.widget.DateWheelLayout
import com.wika.basics.base.BaseActivity
import com.wika.basics.base.BaseDialog
import com.wws.family.R
import com.wws.family.databinding.ActivityMedicineAddBinding
import com.wws.family.db.MedicineBean
import com.wws.family.db.WiKaDataBase
import com.wws.family.dialog.CommonDialog
import com.wws.family.dialog.SelectDialog
import com.wws.family.utils.PublicUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.DecimalFormat


/**
 *@Description:
 *@Date: 2025/1/7 11:41
 *@Author: WangWeiShuo
 */
class MedicineAddActivity: BaseActivity<ActivityMedicineAddBinding>() {

    private var medicineEndTime: String? = null
    private var medicineType = -1
    private var decimalFormat = DecimalFormat("00")
    private var medicineItem: MedicineBean? = null

    override fun initView(savedInstanceState: Bundle?) {
        val extra = intent.getSerializableExtra("medicineItem")
        if(extra != null){
            medicineItem = extra as MedicineBean
            setActionBar(R.drawable.baseline_arrow_back,"编辑药品",R.color.black,R.color.blue_B8DCFF,-1,true,true)
        }else{
            setActionBar(R.drawable.baseline_arrow_back,"新增药品",R.color.black,R.color.blue_B8DCFF,-1,true,true)
        }
        mBinding.btnSelectType.setOnClickListener {
            showMedicineTypeSelect()
        }
        mBinding.btnSelectDate.setOnClickListener {
            selectMedicineTime()
        }
        mBinding.btnSaveMedicine.setOnClickListener {
            saveMedicine()
        }
        if (medicineItem != null){
            showMedicineInfo()
        }
    }

    override fun initData() {

    }

    override fun needFullScreen(): Boolean {
        return false
    }

    override fun actionBarRightClick() {

    }

    private fun showMedicineInfo(){
        mBinding.btnSaveMedicine.setText("更新")
        medicineEndTime = medicineItem?.endTime
        medicineType = medicineItem?.type!!
        mBinding.inputMedicineName.setInputMsg(medicineItem?.name)
        mBinding.inputMedicineName.setInputEnable(false)
        mBinding.inputMedicineFunction.setInputMsg(medicineItem?.function)
        mBinding.inputMedicineMethod.setInputMsg(medicineItem?.method)
        mBinding.inputMedicineTotal.setInputMsg(medicineItem?.total)
        mBinding.inputMedicineRemain.setInputMsg(medicineItem?.remain)
        mBinding.btnSelectDate.text = medicineEndTime
        when(medicineType){
            0 -> {
                mBinding.btnSelectType.text = "药片、胶囊"
            }
            1 -> {
                mBinding.btnSelectType.text = "口服液、糖浆"
            }
            2 -> {
                mBinding.btnSelectType.text = "颗粒、冲剂"
            }
        }

    }

    private fun showMedicineTypeSelect(){
        Log.d("wws", "showMedicineTypeSelect: ")
        PublicUtils.setArrowDownUp(mBinding.ivArrow,false)
        SelectDialog.Builder(this).showTitle("选择药品分类")
            .showContent(PublicUtils.getMedicineTypeList())
            .addSelectListener(object : SelectDialog.OnSelectListener{
                override fun onSelect(pos: Int,name: String) {
                    medicineType = pos
                    mBinding.btnSelectType.text = name
                }

            }).addOnDismissListener(object : BaseDialog.OnDismissListener{
                override fun onDismiss(dialog: BaseDialog?) {
                    PublicUtils.setArrowDownUp(mBinding.ivArrow,true)
                }

            }).showDialog()
    }

    private fun selectMedicineTime() {
        PublicUtils.setArrowDownUp(mBinding.ivArrowTime,false)
        val picker = DatePicker(this)
        val wheelLayout: DateWheelLayout = picker.wheelLayout
        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
        picker.setOnDatePickedListener  { year, month, day ->
            medicineEndTime = "$year-${decimalFormat.format(month)}-${decimalFormat.format(day)}"
            mBinding.btnSelectDate.text = medicineEndTime
        }
        picker.setOnDismissListener {
            PublicUtils.setArrowDownUp(mBinding.ivArrowTime,true)
        }
        wheelLayout.setDateFormatter(UnitDateFormatter())
        wheelLayout.setRange(DateEntity.target(2025, 1, 1), DateEntity.yearOnFuture(10), DateEntity.today())
        picker.wheelLayout.setResetWhenLinkage(false)
        picker.show()
    }

    private fun saveMedicine(){
        val medicineName = mBinding.inputMedicineName.getInputMsg()
        val medicineFunction = mBinding.inputMedicineFunction.getInputMsg()
        val medicineMethod = mBinding.inputMedicineMethod.getInputMsg()
        val medicineTotal = mBinding.inputMedicineTotal.getInputMsg()
        val medicineRemain = mBinding.inputMedicineRemain.getInputMsg()
        if (medicineName.isNullOrEmpty()){
            return showWarningToast("请输入药品名称")
        }
        if (medicineFunction.isNullOrEmpty()){
            return showWarningToast("请输入药品主治功能")
        }
        if (medicineMethod.isNullOrEmpty()){
            return showWarningToast("请输入药品服用方法")
        }
        if (medicineTotal.isNullOrEmpty()){
            return showWarningToast("请输入药品总量")
        }
        if (medicineRemain.isNullOrEmpty()){
            return showWarningToast("请输入药品剩余")
        }
        if (medicineEndTime.isNullOrEmpty()){
            return showWarningToast("请选择药品保质期")
        }
        var content = "是否保存当前药品？"
        if(medicineItem != null){
            content = "是否更新当前药品？"
        }
        CommonDialog.Builder(this).showTitle("提示").showContent(content)
            .setOnSureListener {
                val endDate = medicineEndTime?.replace("-".toRegex(), "")
                val medicineBean = MedicineBean(
                    medicineName,
                    medicineFunction,
                    medicineMethod,
                    medicineTotal,
                    medicineRemain,
                    medicineEndTime,
                    endDate,
                    medicineType
                )
                lifecycleScope.launch(Dispatchers.IO) {
                    if(medicineItem == null) {
                        WiKaDataBase.getInstance().medicineDao().insert(medicineBean)
                    }else{
                        WiKaDataBase.getInstance().medicineDao().updateMedicine(medicineBean)
                    }
                    withContext(Dispatchers.Main){
                        val intent = Intent()
                        intent.putExtra("medicineBean", medicineBean)
                        setResult(1, intent)
                        finish()
                    }
                }
            }.show()
    }

}